package com.traffic.between.service;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.traffic.between.config.BetweenProperties;



public class LinKeServiceImpl {
	private static Logger logger = Logger.getLogger(LinKeServiceImpl.class);
	public static LinKeServiceImpl service = new LinKeServiceImpl();
	
	private static String HOST_ORDER_PATH = BetweenProperties.LINKE_ORDER_URL;
	private static String LINKE_CHANNEL = BetweenProperties.LINKE_CHANNEL;
	private static String LINKE_KEY = BetweenProperties.LINKE_KEY;
	
	
	
	public String order(String pkgNo, String phoneNo, String tradeNo, String notifyUrl) {
		String chOrderId = tradeNo;
        String chId = LINKE_CHANNEL;
        String agCodeProId = pkgNo;
        String type = "101";
        String[] phoneNos = {phoneNo};
        String mobiles= new Gson().toJson(phoneNos);
        String timestamp = System.currentTimeMillis()+"";
       
       
        String waitSig ="agCodeProId="+agCodeProId+"&chId="+chId+"&chOrderId="+chOrderId+"&mobiles="+mobiles+"&timestamp="+timestamp.substring(0,10)+"&type="+type+"&key="+LINKE_KEY;
        String sign = getMD5(waitSig);
        
        String result = "";
        
      
        List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
        pairList.add(new BasicNameValuePair("agCodeProId",agCodeProId));
        pairList.add(new BasicNameValuePair("chId",chId));
        pairList.add(new BasicNameValuePair("chOrderId",chOrderId));
        pairList.add(new BasicNameValuePair("mobiles",mobiles));
        pairList.add(new BasicNameValuePair("timestamp",timestamp.substring(0,10)));
        pairList.add(new BasicNameValuePair("type",type));
        pairList.add(new BasicNameValuePair("sign", sign));
       
		HttpPost httpPost = new HttpPost(HOST_ORDER_PATH);
		CloseableHttpClient client = HttpClients.createDefault();
		logger.info("between- 林科订购请求时的参数: "+pairList);
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
			HttpResponse response = client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			logger.info("between- 林科订购请求时的响应statusCode: " + statusCode+",该订单号为："+tradeNo);
			
			if (200 == statusCode) {
				result = EntityUtils.toString(response.getEntity(), "utf-8");
				logger.info("between- 林科流量订购请求时的响应数据是: " + result+",该订单号为："+tradeNo);
			}else {
				//502  服务器暂时不可用
				Map<String,Object> map = new HashMap<String, Object>();
				map.put("err","-1");
				map.put("msg","["+String.valueOf(statusCode)+"]服务器暂时不可用");
				result = new Gson().toJson(map);
			}
		} catch (Exception e) {
			logger.info("between- 林科流量订购请求时异常: " + e.getMessage());
		}
		return result;
	}

	
	
	
	

	/**
	 * md5加密 ，用于生成sign
	 * 
	 * @param message
	 * @return
	 */
	public static String getMD5(String message) {
		System.out.println("getMD5STR " + message);
		MessageDigest messageDigest = null;
		StringBuffer md5StrBuff = new StringBuffer();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(message.getBytes("UTF-8"));

			byte[] byteArray = messageDigest.digest();
			for (int i = 0; i < byteArray.length; i++) {
				if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
					md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
				else
					md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		} catch (Exception e) {
			throw new RuntimeException();
		}
		System.out.println("getMD5====>" + md5StrBuff.toString().toLowerCase());
		return md5StrBuff.toString().toLowerCase();// 字母小写
	}


	public static void main(String[] args) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("chOrderId", "");//seqId, productCode, pkey, phoneNo , loginName
		params.put("chId", "");//seqId, productCode, pkey, phoneNo , loginName
		//params.put("agCodeProId", "");//seqId, productCode, pkey, phoneNo , loginName
		//params.put("type", "");//seqId, productCode, pkey, phoneNo , phoneNo
		//params.put("mobiles", "");//seqId, productCode, pkey, phoneNo , loginName
		params.put("timestamp", "");//seqId, productCode, pkey, phoneNo , loginName
		//params.put("loginName", "");//seqId, productCode, pkey, phoneNo , loginName
		Object[] keys = params.keySet().toArray();
		Arrays.sort(keys);//升序
		for (Object key : keys) {
			System.out.println(key);
		}

		//endTime loginName phoneNo pkey productCode seqId startTime
		String mobile = "Y62cd5345405d47e4a7317ae2e5e0c";
		System.out.println(mobile.length());
		String[] mobiles = {mobile};
	
		System.out.println(new Gson().toJson(mobiles));
		System.out.println(System.currentTimeMillis()+"");
		String timestamp = System.currentTimeMillis()+"";
		System.out.println(timestamp.substring(0,10));
	}


	
}
